#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include "msgq.h"
#include "tools.h"

Ctos ctos;
Stoc stoc;
Ctos ctos_aim;

void transf(void)
{
	
	char path[PATH_MAX];
	sprintf(path,"%s/%u",ACC_PATH,ctos.acc.id);
	pf("转帐：acc path:%s\n",path);
	int fd = open(path,O_RDWR);
	Ctos mine;
	read(fd,&mine.acc,sizeof(mine.acc));	
	
	if(mine.acc.money>=ctos.acc.money)	
	{
		mine.acc.money = mine.acc.money - ctos.acc.money;
		sprintf(stoc.str,"恭喜您转帐成功，金额为:%f,余额为%f\n",ctos.acc.money,mine.acc.money);
		lseek(fd,0,SEEK_SET);
		write(fd,&mine.acc,sizeof(mine.acc));
		close(fd);
	
	
		char path_to[PATH_MAX];
		sprintf(path_to,"%s/%u",ACC_PATH,ctos.acc.id_to);
		pf("转帐：acc path:%s\n",path_to);
		int fd_to = open(path_to,O_RDWR);
		Ctos your;
		read(fd_to,&your.acc,sizeof(your.acc));
		your.acc.money=your.acc.money+ctos.acc.money;
		lseek(fd_to,0,SEEK_SET);
		write(fd_to,&your.acc,sizeof(your.acc));
		close(fd_to);				
	
	}
	else 
	{	
		sprintf(stoc.str,"余额不足,转帐失败\n");
	}	
	// 返回转账成功信息

	stoc_send(&stoc);
}


int main()
{
	init_msgq();
	for(;;)
	{
		ctos_recv(&ctos,TYPE_TRANSF);
		stoc.type = ctos.pid;
		transf();

	}
}
